package com.proposition.web.paper.export;

import com.baomidou.mybatisplus.toolkit.ArrayUtils;
import com.proposition.commons.model.Paper;
import com.proposition.paper.service.PaperExportService;
import com.proposition.paper.service.PaperService;
import com.proposition.util.PaperUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 试卷导出为Word 模板 导出版本为Word2007 .docx格式
 *
 * @author 杨凯
 * @create 2018-04-16 10:33
 **/
@Slf4j
@Controller
@RequestMapping("/export/word")
public class ExportWordController {

	@Autowired
	private PaperService paperService;

	@Qualifier("exportWenDa")
	@Autowired
	private PaperExportService exportWenDa;

	@Qualifier("exportChangGuiHua")
	@Autowired
	private PaperExportService exportChangGuiHua;

	@Qualifier("exportKeGuanHua")
	@Autowired
	private PaperExportService exportKeGuanHua;

	/**
	 * 导出试卷和答案
	 * 通过试卷Id 导出试卷
	 *
	 * @param request
	 * @param response
	 * @param paperId  试卷Id
	 */
	@Async
	@GetMapping(value = "/{paperId}", produces = "application/octet-stream")
	public void exportPaperAndAnswerByPaperId(HttpServletRequest request, HttpServletResponse response, @PathVariable("paperId") String paperId) {
		Map<String, Object> map = new HashMap<>(10);
		InputStream fis = null;
		OutputStream os = null;
		try {
			if (StringUtils.isEmpty(paperId)) {
				log.warn("试卷导出----》试卷ID不能为空");
			}
			Paper paper = paperService.selectById(paperId);
			//文件生成路径
			String outFilePath = "";
			//文件名称
			String fileName = "";
			//判断试卷类型
			switch (paper.getPaperPattern()) {
				case WEN_DA:
					map = exportWenDa.getPaperAndAnswerById(paperId);
					map.put("paper", paper);
					outFilePath = PaperUtil.outDocx("wenda.ftl", map, request);
					fileName = "第一站问答试卷和答案";
					break;
				case CHANG_GUI:
					map = exportChangGuiHua.getPaperAndAnswerById(paperId);
					map.put("paper", paper);
					outFilePath = PaperUtil.outDocx("changguihua.ftl", map, request);
					fileName = "第二站常规化试卷和答案";
					break;
				case KE_GUAN:
					map = exportKeGuanHua.getPaperAndAnswerById(paperId);
					map.put("paper", paper);
					outFilePath = PaperUtil.outDocx("keguanhua.ftl", map, request);
					fileName = "第二站客观化试卷和答案";
					break;
				default:
					break;
			}
			fis = new BufferedInputStream(new FileInputStream(outFilePath));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			// 清空response
			response.reset();
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1") + ".docx");
			os = new BufferedOutputStream(response.getOutputStream());
			os.write(buffer);
		} catch (NullPointerException e) {
			log.warn("试卷导出----》传入试卷Id参数无效");
		} catch (Exception e) {
			log.error("试卷导出===》未知异常[{}]", e.getMessage());
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				log.error("试卷导出===》试卷导出流关闭异常[{}]", e.getMessage());
			}
		}
	}


	/**
	 * 导出试卷（仅试卷）
	 *
	 * @param paperIds 试卷Id
	 * @param request
	 * @param response
	 */
	@Async
	@GetMapping(value = "/paper", produces = "application/octet-stream")
	public void exportPaperByIds(String[] paperIds, HttpServletRequest request, HttpServletResponse response) {
		InputStream fis = null;
		OutputStream os = null;
		List<Object> list = new ArrayList<>();
		if (ArrayUtils.isEmpty(paperIds)) {
			log.warn("试卷导出----》试卷ID不能为空");
		}
		try {
			//文件生成路径
			String outFilePath = "";
			//文件名称
			String fileName = "";
			//判断试卷类型
			for (String paperId : paperIds) {
				Map<String, Object> map = new HashMap<>(10);
				Paper paper = paperService.selectById(paperId);
				switch (paper.getPaperPattern()) {
					case WEN_DA:
						map = exportWenDa.getPaperAndAnswerById(paperId);
						map.put("paper", paper);
						list.add(map);
						map.put("paperList", list);
						outFilePath = PaperUtil.outDocx("wenda1.ftl", map, request);
						fileName = "第一站问答试卷";
						break;
					case CHANG_GUI:
						map = exportChangGuiHua.getPaperAndAnswerById(paperId);
						map.put("paper", paper);
						list.add(map);
						map.put("paperList", list);
						outFilePath = PaperUtil.outDocx("changguihua1.ftl", map, request);
						fileName = "第二站常规化试卷";
						break;
					case KE_GUAN:
						map = exportKeGuanHua.getPaperAndAnswerById(paperId);
						map.put("paper", paper);
						list.add(map);
						map.put("paperList", list);
						outFilePath = PaperUtil.outDocx("keguanhua1.ftl", map, request);
						fileName = "第二站客观化试卷";
						break;
					default:
						break;
				}
			}
			fis = new BufferedInputStream(new FileInputStream(outFilePath));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			// 清空response
			response.reset();
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1") + ".docx");
			os = new BufferedOutputStream(response.getOutputStream());
			os.write(buffer);
		} catch (NullPointerException e) {
			log.warn("试卷导出----》传入试卷Id参数无效");
		} catch (Exception e) {
			log.error("试卷导出===》未知异常[{}]", e.getMessage());
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				log.error("试卷导出===》试卷导出流关闭异常", e);
			}
		}
	}

	/**
	 * 导出试卷（试卷和答案）
	 * @param paperIds 试卷Id
	 * @param request
	 * @param response
	 */
	@Async
	@GetMapping(value = "/paperAndAnswer", produces = "application/octet-stream")
	public void exportPaperAndAnswerByIds(String[] paperIds, HttpServletRequest request, HttpServletResponse response) {
		InputStream fis = null;
		OutputStream os = null;
		List<Object> list = new ArrayList<>();
		if (ArrayUtils.isEmpty(paperIds)) {
			log.warn("试卷导出----》试卷ID不能为空");
		}
		try {
			//文件生成路径
			String outFilePath = "";
			//文件名称
			String fileName = "";
			//判断试卷类型
			for (String paperId : paperIds) {
				Map<String, Object> map = new HashMap<>(10);
				Paper paper = paperService.selectById(paperId);
				switch (paper.getPaperPattern()) {
					case WEN_DA:
						map = exportWenDa.getPaperAndAnswerById(paperId);
						map.put("paper", paper);
						list.add(map);
						map.put("paperList", list);
						outFilePath = PaperUtil.outDocx("wenda2.ftl", map, request);
						fileName = "第一站问答试卷和答案";
						break;
					case CHANG_GUI:
						map = exportChangGuiHua.getPaperAndAnswerById(paperId);
						map.put("paper", paper);
						list.add(map);
						map.put("paperList", list);
						outFilePath = PaperUtil.outDocx("changguihua2.ftl", map, request);
						fileName = "第二站常规化试卷和答案";
						break;
					case KE_GUAN:
						map = exportKeGuanHua.getPaperAndAnswerById(paperId);
						map.put("paper", paper);
						list.add(map);
						map.put("paperList", list);
						outFilePath = PaperUtil.outDocx("keguanhua2.ftl", map, request);
						fileName = "第二站客观化试卷和答案";
						break;
					default:
						break;
				}
			}
			fis = new BufferedInputStream(new FileInputStream(outFilePath));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			// 清空response
			response.reset();
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1") + ".docx");
			os = new BufferedOutputStream(response.getOutputStream());
			os.write(buffer);
		} catch (NullPointerException e) {
			log.warn("试卷导出----》传入试卷Id参数无效");
		} catch (Exception e) {
			log.error("试卷导出===》未知异常[{}]", e.getMessage());
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				log.error("试卷导出===》试卷导出流关闭异常[{}]", e.getMessage());
			}
		}
	}

}
